<template>
  <div class="admin-profile">
    <!-- 页面标题 -->
    <div class="mb-6">
      <h1 class="text-2xl font-bold text-gray-800">个人资料</h1>
      <p class="text-gray-600 mt-1">管理您的个人信息和账户设置</p>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
      <!-- 左侧个人信息卡片 -->
      <div class="lg:col-span-1">
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <div class="text-center">
            <!-- 头像 -->
            <div class="relative inline-block mb-4">
              <el-avatar :size="100" :src="getImageUrl(userStore.userInfo?.avatar)" class="border-4 border-white shadow-lg">
                <i class="fas fa-user text-4xl text-gray-400"></i>
              </el-avatar>
              <button 
                @click="showAvatarDialog = true"
                class="absolute bottom-0 right-0 bg-primary text-white rounded-full w-8 h-8 flex items-center justify-center hover:bg-primary-dark transition-colors"
              >
                <i class="fas fa-camera text-sm"></i>
              </button>
            </div>
            
            <!-- 基本信息 -->
            <h3 class="text-xl font-semibold text-gray-800 mb-1">{{ userStore.userInfo?.username }}</h3>
            <p class="text-gray-500 mb-2">{{ userStore.userInfo?.email }}</p>
            <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
              <i class="fas fa-shield-alt mr-1"></i>
              管理员
            </span>
          </div>

          <!-- 统计信息 -->
          <div class="mt-6 pt-6 border-t border-gray-200">
            <div class="grid grid-cols-2 gap-4 text-center">
              <div>
                <div class="text-2xl font-bold text-primary">{{ adminStats.loginCount || 0 }}</div>
                <div class="text-sm text-gray-500">登录次数</div>
              </div>
              <div>
                <div class="text-2xl font-bold text-primary">{{ adminStats.operationCount || 0 }}</div>
                <div class="text-sm text-gray-500">操作次数</div>
              </div>
            </div>
          </div>

          <!-- 最后登录信息 -->
          <div class="mt-4 pt-4 border-t border-gray-100 space-y-2">
            <div class="flex items-center justify-between text-sm">
              <span class="flex items-center text-gray-600">
                <i class="fas fa-clock mr-2"></i>
                最后登录:
              </span>
              <span class="text-gray-800">{{ formatLastLoginTime(adminStats.lastLoginTime) }}</span>
            </div>
            <div class="flex items-center justify-between text-sm">
              <span class="flex items-center text-gray-600">
                <i class="fas fa-map-marker-alt mr-2"></i>
                登录IP:
              </span>
              <span class="text-gray-800">{{ adminStats.lastLoginIp || '未知' }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧表单区域 -->
      <div class="lg:col-span-2">
        <div class="bg-white rounded-lg shadow-sm border border-gray-200">
          <!-- 标签页 -->
          <div class="border-b border-gray-200">
            <nav class="flex space-x-8 px-6">
              <button
                v-for="tab in tabs"
                :key="tab.key"
                @click="activeTab = tab.key"
                :class="[
                  'py-4 px-1 border-b-2 font-medium text-sm transition-colors',
                  activeTab === tab.key
                    ? 'border-primary text-primary'
                    : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                ]"
              >
                <i :class="tab.icon" class="mr-2"></i>
                {{ tab.label }}
              </button>
            </nav>
          </div>

          <!-- 标签页内容 -->
          <div class="p-6">
            <!-- 基本信息 -->
            <div v-if="activeTab === 'basic'" class="space-y-6">
              <h3 class="text-lg font-medium text-gray-900 mb-4">基本信息</h3>
              
              <el-form :model="profileForm" label-width="120px" class="space-y-4">
                <el-form-item label="用户名">
                  <el-input v-model="profileForm.username" placeholder="请输入用户名" />
                </el-form-item>
                
                <el-form-item label="真实姓名">
                  <el-input v-model="profileForm.realName" placeholder="请输入真实姓名" />
                </el-form-item>
                
                <el-form-item label="邮箱">
                  <el-input v-model="profileForm.email" placeholder="请输入邮箱" />
                </el-form-item>
                
                <el-form-item label="手机号">
                  <el-input v-model="profileForm.phone" placeholder="请输入手机号" />
                </el-form-item>
                
                <el-form-item label="性别">
                  <el-radio-group v-model="profileForm.gender">
                    <el-radio :label="1">男</el-radio>
                    <el-radio :label="2">女</el-radio>
                    <el-radio :label="0">未设置</el-radio>
                  </el-radio-group>
                </el-form-item>
                
                <el-form-item label="生日">
                  <el-date-picker
                    v-model="profileForm.birthday"
                    type="date"
                    placeholder="选择日期"
                    style="width: 100%"
                  />
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" @click="saveProfile" :loading="saving">
                    <i class="fas fa-save mr-2"></i>保存修改
                  </el-button>
                  <el-button @click="resetProfile">
                    <i class="fas fa-undo mr-2"></i>重置
                  </el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- 安全设置 -->
            <div v-if="activeTab === 'security'" class="space-y-6">
              <h3 class="text-lg font-medium text-gray-900 mb-4">安全设置</h3>
              
              <!-- 修改密码 -->
              <div class="bg-gray-50 rounded-lg p-4">
                <h4 class="font-medium text-gray-900 mb-3">修改密码</h4>
                <el-form :model="passwordForm" label-width="120px" class="space-y-4">
                  <el-form-item label="当前密码">
                    <el-input v-model="passwordForm.currentPassword" type="password" placeholder="请输入当前密码" />
                  </el-form-item>
                  
                  <el-form-item label="新密码">
                    <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" />
                  </el-form-item>
                  
                  <el-form-item label="确认密码">
                    <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" />
                  </el-form-item>
                  
                  <el-form-item>
                    <el-button type="primary" @click="changePassword" :loading="changingPassword">
                      <i class="fas fa-key mr-2"></i>修改密码
                    </el-button>
                  </el-form-item>
                </el-form>
              </div>
            </div>

            <!-- 权限信息 -->
            <div v-if="activeTab === 'permissions'" class="space-y-6">
              <h3 class="text-lg font-medium text-gray-900 mb-4">权限信息</h3>
              
              <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <div class="flex items-center mb-3">
                  <i class="fas fa-info-circle text-blue-500 mr-2"></i>
                  <span class="font-medium text-blue-900">当前角色权限</span>
                </div>
                <div class="grid grid-cols-2 md:grid-cols-3 gap-3">
                  <div v-for="permission in userPermissions" :key="permission" class="flex items-center">
                    <i class="fas fa-check text-green-500 mr-2"></i>
                    <span class="text-sm text-gray-700">{{ permission }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 头像上传对话框 -->
    <el-dialog v-model="showAvatarDialog" title="更换头像" width="400px">
      <div class="text-center">
        <div class="mb-4">
          <el-avatar :size="120" :src="previewAvatar || getImageUrl(userStore.userInfo?.avatar)">
            <i class="fas fa-user text-4xl text-gray-400"></i>
          </el-avatar>
        </div>
        <el-upload
          class="avatar-uploader"
          action="#"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :on-change="handleAvatarChange"
          :auto-upload="false"
          accept="image/*"
          ref="avatarUpload"
        >
          <el-button type="primary">
            <i class="fas fa-upload mr-2"></i>选择图片
          </el-button>
        </el-upload>
        <p class="text-sm text-gray-500 mt-2">支持 JPG、PNG 格式，文件大小不超过 20MB</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAvatarDialog = false">取消</el-button>
          <el-button type="primary" @click="handleUploadAvatar" :loading="uploadingAvatar">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { adminAPI } from '@/api/admin'

const userStore = useUserStore()

// 响应式数据
const activeTab = ref('basic')
const saving = ref(false)
const changingPassword = ref(false)
const showAvatarDialog = ref(false)
const previewAvatar = ref('')
const uploadingAvatar = ref(false)
const avatarUpload = ref(null)
const selectedAvatarFile = ref(null)

// 标签页配置
const tabs = [
  { key: 'basic', label: '基本信息', icon: 'fas fa-user' },
  { key: 'security', label: '安全设置', icon: 'fas fa-shield-alt' },
  { key: 'permissions', label: '权限信息', icon: 'fas fa-key' }
]

// 管理员统计信息
const adminStats = reactive({
  loginCount: 0,
  operationCount: 0
})

// 个人资料表单
const profileForm = reactive({
  username: '',
  realName: '',
  email: '',
  phone: '',
  gender: 0,
  birthday: null,
  department: '',
  position: ''
})

// 密码修改表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 用户权限列表
const userPermissions = ref([
  '用户管理', '图书管理', '分类管理', '订单管理',
  '新闻管理', '评论管理', '数据统计', '系统设置'
])

// 方法
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 格式化最后登录时间
const formatLastLoginTime = (dateTime) => {
  if (!dateTime || dateTime === '未知') {
    return '暂无'
  }

  try {
    const date = new Date(dateTime)
    if (isNaN(date.getTime())) {
      return '暂无'
    }

    const now = new Date()
    const diff = now - date
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))
    const hours = Math.floor(diff / (1000 * 60 * 60))
    const minutes = Math.floor(diff / (1000 * 60))

    if (days > 0) {
      return `${days}天前`
    } else if (hours > 0) {
      return `${hours}小时前`
    } else if (minutes > 0) {
      return `${minutes}分钟前`
    } else {
      return '刚刚'
    }
  } catch (error) {
    return '暂无'
  }
}

// 获取图片URL
const getImageUrl = (url) => {
  if (!url) return ''

  // 如果是完整的URL，直接返回
  if (url.startsWith('http')) {
    return url
  }

  // 如果是上传的文件路径
  if (url.startsWith('/uploads/')) {
    return `http://localhost:8081/api${url}`
  }

  // 如果是静态资源路径
  if (url.startsWith('/assets/')) {
    return `http://localhost:8081/api${url}`
  }

  // 其他情况，添加API前缀
  return `/api${url}`
}

// 格式化日期用于提交（避免时区问题）
const formatDateForSubmit = (date) => {
  if (!date) return null
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

const saveProfile = async () => {
  saving.value = true
  try {
    // 准备提交的数据
    const profileData = {
      username: profileForm.username,
      realName: profileForm.realName,
      email: profileForm.email,
      phone: profileForm.phone,
      gender: profileForm.gender,
      birthDate: profileForm.birthday ? formatDateForSubmit(profileForm.birthday) : null
    }

    // 调用API保存个人资料
    const response = await adminAPI.updateAdminProfile(profileData)
    if (response.code === 200) {
      ElMessage.success('个人资料保存成功')
      // 更新用户store中的信息
      await loadAdminProfile()
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    ElMessage.error('保存失败：' + (error.response?.data?.message || error.message))
  } finally {
    saving.value = false
  }
}

const resetProfile = () => {
  // 重置为用户信息
  Object.assign(profileForm, {
    username: userStore.userInfo?.username || '',
    realName: userStore.userInfo?.realName || '',
    email: userStore.userInfo?.email || '',
    phone: userStore.userInfo?.phone || '',
    gender: userStore.userInfo?.gender || 0,
    birthday: userStore.userInfo?.birthday || null,
    department: userStore.userInfo?.department || '',
    position: userStore.userInfo?.position || ''
  })
}

const changePassword = async () => {
  if (!passwordForm.currentPassword || !passwordForm.newPassword || !passwordForm.confirmPassword) {
    ElMessage.error('请填写完整的密码信息')
    return
  }

  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    ElMessage.error('两次输入的密码不一致')
    return
  }

  if (passwordForm.newPassword.length < 6) {
    ElMessage.error('新密码长度不能少于6位')
    return
  }

  if (passwordForm.currentPassword === passwordForm.newPassword) {
    ElMessage.error('新密码不能与当前密码相同')
    return
  }

  changingPassword.value = true
  try {
    const response = await adminAPI.changePassword({
      currentPassword: passwordForm.currentPassword,
      newPassword: passwordForm.newPassword,
      confirmPassword: passwordForm.confirmPassword
    })

    if (response.code === 200) {
      ElMessage.success('密码修改成功')
      // 重置表单
      Object.assign(passwordForm, {
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      })
    } else {
      ElMessage.error(response.message || '密码修改失败')
    }
  } catch (error) {
    ElMessage.error((error.response?.data?.message || error.message))
  } finally {
    changingPassword.value = false
  }
}



const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 20

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 20MB!')
    return false
  }
  return true
}

const handleAvatarChange = (file) => {
  selectedAvatarFile.value = file
  const reader = new FileReader()
  reader.onload = (e) => {
    previewAvatar.value = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

const handleUploadAvatar = async () => {
  if (!selectedAvatarFile.value) {
    ElMessage.error('请先选择头像文件')
    return
  }

  uploadingAvatar.value = true
  try {
    const formData = new FormData()
    formData.append('file', selectedAvatarFile.value.raw)

    const response = await adminAPI.uploadAvatar(formData)
    if (response.code === 200) {
      ElMessage.success('头像上传成功')
      // 更新用户信息
      await loadAdminProfile()
      showAvatarDialog.value = false
      previewAvatar.value = ''
      selectedAvatarFile.value = null
    } else {
      ElMessage.error(response.message || '头像上传失败')
    }
  } catch (error) {
    ElMessage.error('头像上传失败：' + (error.response?.data?.message || error.message))
  } finally {
    uploadingAvatar.value = false
  }
}



// 重置表单数据
const resetProfileForm = () => {
  Object.assign(profileForm, {
    username: '',
    realName: '',
    email: '',
    phone: '',
    gender: 0,
    birthday: null,
    department: '',
    position: ''
  })
}

// 加载管理员个人资料
const loadAdminProfile = async () => {
  try {
    const response = await adminAPI.getAdminProfile()
    if (response.code === 200) {
      const profile = response.data
      // 更新表单数据
      Object.assign(profileForm, {
        username: profile.username || '',
        realName: profile.realName || '',
        email: profile.email || '',
        phone: profile.phone || '',
        gender: profile.gender || 0,
        birthday: profile.birthDate ? new Date(profile.birthDate) : null,
        department: profile.department || '',
        position: profile.position || ''
      })

      // 更新用户store
      userStore.updateUserInfo({
        ...userStore.userInfo,
        username: profile.username,
        email: profile.email,
        phone: profile.phone,
        realName: profile.realName,
        avatar: profile.avatar,
        gender: profile.gender,
        birthDate: profile.birthDate
      })
    }
  } catch (error) {
    console.error('加载管理员资料失败：', error)
    ElMessage.error('加载个人资料失败')
  }
}

// 加载管理员统计信息
const loadAdminStats = async () => {
  try {
    const response = await adminAPI.getAdminStats()
    if (response.code === 200) {
      Object.assign(adminStats, response.data)
    }
  } catch (error) {
    console.error('加载统计信息失败：', error)
  }
}

// 监听用户信息变化，当用户切换时重新加载数据
watch(() => userStore.userInfo?.id, async (newUserId, oldUserId) => {
  if (newUserId && newUserId !== oldUserId) {
    // 用户切换了，重新加载数据
    resetProfileForm()
    await loadAdminProfile()
    await loadAdminStats()
  }
}, { immediate: false })

// 初始化数据
onMounted(async () => {
  // 先重置表单数据，避免显示之前用户的信息
  resetProfileForm()
  // 然后加载当前用户的数据
  await loadAdminProfile()
  await loadAdminStats()
})
</script>

<style scoped>
.admin-profile {
  max-width: 80rem;
  margin-left: auto;
  margin-right: auto;
}

.avatar-uploader {
  display: block;
}
</style>
